Euler Problem 125

The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: $$6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2.$$

There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is 4164. Note that $1 = 0^2 + 1^2$ has not been included as this problem is concerned with the squares of positive integers.

Find the sum of all the numbers less than $10^8$ that are both palindromic and can be written as the sum of consecutive squares.


In [1]:
def palindrome(n):
    s = str(n)
    return s == s[::-1]

f = lambda n: n*(n+1)*(2*n+1)//6
F = {0: f(0), 1: f(1)}
seen = set()

for n in range(2, 10000):
    F[n] = f(n)
    for m in range(n-2, -1, -1):
        p  = F[n] - F[m]
        if p >= 10**8:
            break
        if palindrome(p):
            seen.add(p)
print(sum(seen))


2906969179

In [ ]: